
import storage from './storage';


const getUrlParam = function() {
    const param = {};
    const parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, (m, key, value) => {
        if (value.indexOf('#') > 0) {
            value = value.split('#')[0];
        }
        param[key] = value;
    });
    return param;
};

const getLastParam = function() {
    const urlParams = location.href.split('/');
    const lastParam = urlParams[urlParams.length - 1];
    if (lastParam.indexOf('?')) {
        return lastParam.split('?')[0];
    }
    return lastParam;
};

const toThousands = function(value) {
    let num = (value || 0).toString();
    let result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) { result = num + result; }
    return result;
};

const toPercentage = function(num1, num2) {
    if (!num2) {
        return '0.00%';
    }
    return `${(num1 * 100 / num2).toFixed(2)}%`;
};


const store = {
    getUser() {
        return storage.local.getItem('user');
    },
    setUser(data) {
        storage.local.setItem('user', data);
    },
    setAuthority(data) {
        storage.session.setItem('authority', data);
    },
    getAuthority() {
        return storage.session.getItem('authority');
    },
    clear() {
        storage.session.clear();
        storage.local.clear();
    }
};


export default {
    getUrlParam,
    getLastParam,
    store,
    toThousands,
    toPercentage,
};
